﻿import os
import uuid
#import Image
import ImageFile
from django.http import HttpResponse, Http404
from PIL import Image
from django.http import HttpResponseRedirect
from django.shortcuts import render, render_to_response
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from django.core.serializers.json import DjangoJSONEncoder
from paypal.standard.forms import PayPalPaymentsForm

from models import *
from utils import global_render

from django.core.mail import send_mail, EmailMultiAlternatives

import random
import string
import datetime
import time
from math import log
import settings
from django.utils import simplejson
from django.core import serializers


def index(request):
    i_follows = {}
    categorys = Category.objects.all()
    dmscount = None
    try:
        i_follows = Friends.objects.order_by('integral').filter(follower=User.objects.get(username=request.user))
        users = User.objects.get(username=request.user)
        dmscount = DirectMessage.objects.filter(to_user=request.user, is_read=0).count()
    except:
        i_follows = {}
        users = None
        user_profile = None
    return render(request, 'index.html', {'users': users,
                                          'i_follows': i_follows,
                                          'dmscount': dmscount,
                                          'categorys': categorys})


def getArticle(request):
    offset = request.GET['no']
    type = request.GET['type']
    category = request.GET['category']
    ad = None
    if category == 'ALL':#选择所有分类
        category = ''
    order_by = 'integral'
    if type == 'new':
        order_by = '-date'
    if type == 'pop':
        order_by = '-up'
    if category == '':
        articles = Article.objects.order_by(order_by)[int(offset):int(offset) + 10]
    else:
        categoryObj = Category.objects.filter(name=category)
        ads = Ad.objects.filter(category=categoryObj, start_date__lte=datetime.datetime.now(),
                                end_date__gte=datetime.datetime.now())
        if ads is not None:
            ad = ads[0]
        articles = Article.objects.filter(category=category).order_by(order_by)[int(offset):int(offset) + 10]
    return global_render(request, 'cell.html', {'articles': articles, 'ad': ad})


#个人主页的文章列表
def getPersonalArticle(request, id):
    try:
        if id:
            users = User.objects.get(pk=id)
        else:
            users = User.objects.get(username=request.user)
        offset = request.GET['no']
        category = request.GET['category']
        if category == 'ALL':#选择所有分类
            category = ''
        if category == '':
            articles = Article.objects.filter(user_id=users.id).order_by('-date')[int(offset):int(offset) + 10]
        else:
            articles = Article.objects.filter(category=category, user_id=users.id).order_by('-date')[
                       int(offset):int(offset) + 10]
        return global_render(request, 'cell.html', {'articles': articles})
    except:
        return global_render(request, 'login.html')


def article_detail(request, id):
    users = None
    boardManagerFlag = 0
    board = None
    if request.user.username != '':
        users = request.user
    article = Article.objects.get(pk=id)
    if article is not None:
        #查看是否为二级分类
        boardName = article.sub
        boardUrl = ''
        if boardName:
            boardUrl = '/boardArticleIndex/' + boardName + '/'
            category = Category.objects.get(name=article.category);
            board = Board.objects.get(name=boardName,category=category)
            if users.id==board.manager.id:
                boardManagerFlag = '1'
        article_user = article.user
        hasFollowed = 0
        if users is not None:
            friends = Friends.objects.filter(user=article_user, follower=users)
            if len(friends) > 0:
                hasFollowed = 1
        article_count = Article.objects.filter(user=article_user).count()
        totalCount = Comment.objects.filter(article=article).count()
        import math

        if 0 == totalCount:
            pageCount = 0
        else:
            pageCount = int(math.ceil(float(totalCount) / 3))
        #categorys = Category.objects.all()
        #articleCount = Article.objects.filter(user=request.user).count()
        boradCount = Board.objects.filter(manager=article_user).count()
        commentCount = Comment.objects.filter(article=article).count()
        return global_render(request, 'detail.html', {'users': users,
                                                      'article': article,
                                                      'article_user': article_user,
                                                      'totalCount': totalCount,
                                                      'pageCount': pageCount,
                                                      'article_count': article_count,
                                                      'hasFollowed': hasFollowed, 'boardName': boardName,
                                                      'boardManagerFlag':boardManagerFlag,
                                                      'articleUrl': boardUrl,'board':board,
                                                      'articleCount': article_count, 'boradCount': boradCount,
                                                      'commentCount': commentCount})


def editArticleIndex(request, id):
    users = None
    if request.user.username != '':
        users = request.user
    try:
        article = Article.objects.get(pk=id)
    except:
        raise Http404
    category = Category.objects.order_by('id')
    if article is not None:
        if (article.link is not None and article.link) or (article.video is not None and article.video):
            type = 'link'
        else:
            type = 'text'
        form = ArticleForm(data={"category": article.category, 'title': article.title, 'content': article.content,
                                 'link': article.link, 'video': article.video, 'imgs': article.imgs})
        return global_render(request, 'editArticle.html', {'users': users,
                                                           'article': article, 'category': category, 'form': form,
                                                           'type': type, 'boardName': article.sub})


def editArticle(request):
    articleId = request.POST["articleId"]
    form = ArticleForm(request.POST)
    if form.is_valid():
        data = form.cleaned_data
        if articleId is not None:
            try:
                article = Article.objects.get(pk=articleId)
            except:
                raise Http404
            if article is not None:
                article.title = data['title']
                article.content = data['content']
                article.category = data['category']
                article.link = data['link']
                article.imgs = data['imgs']
                article.save()
                return HttpResponseRedirect('/personalIndex/' + str(request.user.id) + '/')
        raise Http404
    else:
        category = Category.objects.order_by('id')
        return global_render(request, 'editArticle.html',
                             {'form': form, 'category': category, 'users': request.user, 'message': form.errors})


@login_required(login_url='/login/')
def saveComment(request):
    content = request.GET['content']
    article_id = request.GET['articleId']
    article = Article.objects.get(pk=article_id)
    user = request.user
    date = datetime.datetime.now()
    if article is not None:
        try:
            comment = Comment(content=content, article_id=article.id, user_id=user.id, date=date)
            comment.save()
            return HttpResponse("1")
        except:
            return HttpResponse(u'系统繁忙,请稍候再试!')


def commentPage(request):
    articleId = request.GET['articleId']
    pagenumber = request.GET['pagenumber']
    if articleId is not None and pagenumber is not None:
        offset = 3
        startnum = (int(pagenumber) - 1) * offset
        endnum = int(pagenumber) * offset
        list = Comment.objects.filter(article_id=articleId)[startnum:endnum]
        up = {}
        for co in list:
            userPofile = UserProfile.objects.get(user_id=co.user.id)
            up[int(userPofile.user_id)] = str(userPofile.avatar)
        if list:
            return global_render(request, 'commentPage.html', {'list': list, 'page': int(pagenumber), 'upList': up})
        else:
            return HttpResponse("")

    else:
        return HttpResponse("")


def signup(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            users = User.objects.filter(email=request.POST['email'])
            if not users:
                user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'],
                                                form.cleaned_data['password'])
                user.save()
                user_profile = UserProfile(user=user)
                user_profile.avatar = "/photos/avatar.gif"
                user_profile.save()
                user = authenticate(username=request.POST['username'], password=request.POST['password'])
                login(request, user)
                #todo发邮件
                #发送email
                try:
                    send_mail('Register djangosns account successful!',
                              'You had registered djangosns account successfully!',
                              'suyu8776@163.com', [form.cleaned_data['email']], fail_silently=False)
                except:
                    pass
            else:
                return global_render(request, 'signup.html', {'form': form, 'error': 'Email has been registered!'})
            return HttpResponseRedirect('/')
        return global_render(request, 'signup.html', {'form': form})
    if request.method == 'GET':
        form = UserForm()
        return global_render(request, 'signup.html', {'form': form})


def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        user = authenticate(username=request.POST['username'], password=request.POST['password'])
        if user is not None:
            if user.is_active:
                login(request, user)
                if request.POST['next'] != '0':
                    return HttpResponseRedirect(request.POST['next'])
                else:
                    return HttpResponseRedirect('/')
        else:
            return global_render(request, "login.html", {'form': form, 'error': 'username or password is invalid!'})
    else:
        form = LoginForm()
        next = '0'
        if request.GET.has_key('next'):
            next = request.GET['next']
        return global_render(request, "login.html", {'form': form, 'next': next})


def logout_view(request):
    logout(request)
    return HttpResponseRedirect('/')


def forget_password(request):
    if request.method == 'POST':
        email = request.POST['email']
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            user = None
        if user:
            #生成一个字符串,长度为10到20
            activation_key = random_string(random.randint(10, 20));
            #将用户名,字符串,当前时间存入数据库
            #检测是否存在
            findPasses = UserProfile.objects.filter(user=user)
            if findPasses: #已经存在
                findPass = findPasses[0]
                findPass.activation_key = activation_key #更新key
            else:
                findPass = UserProfile(user=user, activation_key=activation_key)
            findPass.save()
            #发送email
            #th = Thread(target=send_mail,
            #    args=('Reset password!Not reply! ',
            #        'click the url http://djangosns/account/resetpassowrd/'+activation_key,
            #        [email]))
            #th.start()
            subject, from_email, to = 'Djangosns reset password', 'suyu8776@163.com',
            text_content = 'This is an reset password email.'
            html_content = 'click <a href="http://localhost:8000/resetpass/' + activation_key + '/">http://localhost:8000/resetpass/' + activation_key + '/</a> to reset password'
            msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
            msg.attach_alternative(html_content, "text/html")
            msg.send()
            #跳转页面
            return render_to_response('emailDes.html')
        else:
            #用户不存在的操作
            form = ResetPassForm()
            return global_render(request, 'forget_password.html', {'form': form, 'error': 'email is not exists!'})
    else:
        form = ResetPassForm()
        return global_render(request, "forget_password.html", {'form': form})


def begin_reset_password(request, activation_key):
    findPasses = UserProfile.objects.filter(activation_key=activation_key)
    if findPasses:
        findPass = findPasses[0]
        #将User存入session或其他...
        user = findPass.user
        request.session['findpasser'] = user
        #定向到重置密码解密
        return global_render(request, 'reset_password.html', {'user': user})
    return render_to_response('404.html')


def reset_password(request):
    password = request.POST['password']
    user = request.session['findpasser']
    if user:
        user.set_password(password)
        user.save()
        #修改成功后的操作
        #更新记录
        userProfile = UserProfile.objects.get(user=user)
        userProfile.activation_key = ''
        userProfile.save()
        #删除session
        del request.session['findpasser']
        return HttpResponseRedirect('/login/')
    else:
        return render_to_response('404.html')


def follow(request, id):
    if request.user.username != '':
        user = User.objects.get(id=id)
        follow_user = User.objects.get(username=request.user)
        if user.id != follow_user.id:
            friend = Friends()
            friend.user = user
            friend.follower = follow_user
            friends = Friends.objects.filter(user=user, follower=follow_user)
            if len(friends) <= 0:
                friend.save()
                user_profile = user.userprofile
                user_profile.follow += 1
                user_profile.save()
                follow_user_profile = follow_user.userprofile
                follow_user_profile.followers += 1
                follow_user_profile.save()
        return HttpResponse('Followed!')
    return HttpResponse('You must login first!')


def unfollow(request, id):
    if request.user.username != '':
        user = User.objects.get(id=id)
        follow_user = User.objects.get(username=request.user)
        try:
            friends = Friends.objects.get(user=user, follower=follow_user)
            if friends is not None:
                friends.delete()
                user_profile = follow_user.userprofile
                user_profile.follow -= 1
                user_profile.save()
                follow_user_profile = user.userprofile
                follow_user_profile.followers -= 1
                if follow_user_profile.followers < 0:
                    follow_user_profile.followers = 0
                follow_user_profile.save()
                return HttpResponse('Unfollowed!')
        except:
            return HttpResponse('Unfollowed!')
        return HttpResponse('Unfollowed!')
    return HttpResponse('You must login first!')


def followList(request, id):
    friends = Friends.objects.filter(follower=User.objects.get(id=id))
    return global_render(request, 'followList.html', {'friends': friends})


def followerList(request, id):
    user = User.objects.get(id=id)
    friends = Friends.objects.filter(user=user)
    return global_render(request, 'followerList.html', {'friends': friends})


@login_required(login_url='/login/')
def setting(request):
    if request.method == 'POST':
        userProfile = None
        try:
            userProfile = request.user.userprofile#UserProfile.objects.get(user=User.objects.get(username=request.user))
        except:
            userProfile = UserProfile()
        userProfile.user = request.user #User.objects.get(username=request.user)
        userProfile.paypal = request.POST['paypal']
        if 'avatar' in request.FILES:
            file = request.FILES.get("avatar", None)
            path = os.path.join(settings.MEDIA_ROOT, 'photos/user')
            file_name = str(request.user.id) + file.name[file.name.rfind('.'):]
            path_file = os.path.join(path, file_name)
            parser = open(path_file, 'wb+')
            for chunk in file.chunks():
                parser.write(chunk)
                parser.close()
            size = 85, 85
            im = Image.open(path_file)
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(path_file)
            userProfile.avatar = path_file
        userProfile.save()
        return HttpResponseRedirect('/')
    else:
        user = User.objects.get(username=request.user)
        try:
            userProfile = UserProfile.objects.get(user=user)
        except:
            userProfile = None
        return global_render(request, 'setting.html', {'userProfile': userProfile})


def random_string(num):
    passward = ''
    seed = string.letters + string.digits
    for i in xrange(num):
        passward += seed[random.randrange(1, len(seed))]
    return passward


@login_required(login_url='/login/')
def articleIndex(request):
    form = ArticleForm()
    category = Category.objects.order_by('id')    #文章类型查询
    users = User.objects.get(username=request.user)
    articleCount = Article.objects.filter(user=request.user).count()
    boradCount = Board.objects.filter(manager=request.user).count()
    return global_render(request, 'articleAdd.html',
                         {'form': form, 'category': category, 'users': users, 'articleCount': articleCount,
                          'boradCount': boradCount})


@login_required(login_url='/login/')
def addArticle(request):
    articleCount = Article.objects.filter(user=request.user).count()
    boradCount = Board.objects.filter(manager=request.user).count()
    if request.method == 'POST':
        category = Category.objects.order_by('id')    #文章类型查询
        form = ArticleForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            currer_datetime = datetime.datetime.now()
            year = datetime.datetime.strftime(currer_datetime, "%Y")
            week = datetime.datetime.strftime(currer_datetime, "%W")
            #判断文章发表日期
            user_profile = request.user.userprofile
            if user_profile:
                startDate = user_profile.start_date
                endDate = user_profile.end_dete
                if startDate and endDate:
                    c = datetime.datetime.strftime(currer_datetime, "%Y-%m-%d %H:%M:%S")
                    startDate = datetime.datetime.strftime(startDate, "%Y-%m-%d %H:%M:%S")
                    endDate = datetime.datetime.strftime(endDate, "%Y-%m-%d %H:%M:%S")
                    if c > startDate and endDate > c:
                        limit_date = user_profile.limit_article_date
                        if limit_date:
                            l = datetime.datetime.strftime(limit_date, "%Y-%m-%d %H:%M:%S")
                            if l > c:
                                message = u'操作过于频繁，暂时不能发帖'
                                return global_render(request, 'articleAdd.html',
                                                     {'form': form, 'category': category, 'message': message,
                                                      'users': request.user, 'articleCount': articleCount,
                                                      'boradCount': boradCount})
                            else:
                                flag = True
                        else:#limit_date为空时也可发布文章
                            flag = True
                        if flag:
                            article = Article(title=data['title'], link=data['link'], content=data['content'],
                                              video=data['video'],
                                              imgs=data['imgs'], down=0, up=0, category=data['category'], integral=0,
                                              date=currer_datetime, year=year, week=week,
                                              user=request.user)
                            article.save()

                            return HttpResponseRedirect('/personalIndex/' + str(request.user.id) + '/')

                    else:
                        message = u'您还不是高级会员，暂不能发贴'
                        return global_render(request, 'articleAdd.html',
                                             {'form': form, 'category': category, 'message': message,
                                              'users': request.user, 'articleCount': articleCount,
                                              'boradCount': boradCount})
                else:
                    message = u'您还不是高级会员，暂不能发贴'
                    return global_render(request, 'articleAdd.html',
                                         {'form': form, 'category': category, 'message': message,
                                          'users': request.user, 'articleCount': articleCount,
                                          'boradCount': boradCount})
            else:
                return global_render(request, 'login.html')
        else:
            return global_render(request, 'articleAdd.html',
                                 {'form': form, 'category': category, 'users': request.user, 'message': form.errors,
                                  'articleCount': articleCount, 'boradCount': boradCount})
    else:
        users = request.user
        form = ArticleForm()
        return global_render(request, 'articleAdd.html',
                             {'users': users, 'form': form, 'articleCount': articleCount, 'boradCount': boradCount})


#圈子文章
@login_required(login_url='/login/')
def boardArticleIndex(request, boardName):
    if boardName:
        form = ArticleForm()
        users = User.objects.get(username=request.user)
        articleCount = Article.objects.filter(user=request.user).count()
        boradCount = Board.objects.filter(manager=request.user).count()
        return global_render(request, 'articleAdd.html', {'form': form, 'boardName': boardName, 'users': users,
                                                          'articleUrl': '/boardArticleIndex/' + boardName + '/',
                                                          'articleCount': articleCount, 'boradCount': boradCount})


@login_required(login_url='/login/')
def boardAddArticle(request, boardName):
    articleCount = Article.objects.filter(user=request.user).count()
    boardCount = Board.objects.filter(manager=request.user).count()
    if boardName:
        if request.method == 'POST':
            form = ArticleForm(request.POST)
            if form.is_valid():
                data = form.cleaned_data
                currer_datetime = datetime.datetime.now()
                year = datetime.datetime.strftime(currer_datetime, "%Y")
                week = datetime.datetime.strftime(currer_datetime, "%W")
                #判断文章发表日期
                user_profile = request.user.userprofile
                if user_profile:
                    startDate = user_profile.start_date
                    endDate = user_profile.end_dete
                    if startDate and endDate:
                        c = datetime.datetime.strftime(currer_datetime, "%Y-%m-%d %H:%M:%S")
                        startDate = datetime.datetime.strftime(startDate, "%Y-%m-%d %H:%M:%S")
                        endDate = datetime.datetime.strftime(endDate, "%Y-%m-%d %H:%M:%S")
                        if c > startDate and endDate > c:
                            limit_date = user_profile.limit_article_date
                            if limit_date:
                                l = datetime.datetime.strftime(limit_date, "%Y-%m-%d %H:%M:%S")
                                if l > c:
                                    message = u'操作过于频繁，暂时不能发帖'
                                    return global_render(request, 'articleAdd.html',
                                                         {'form': form, 'boardName': boardName, 'message': message,
                                                          'users': request.user, 'articleCount': articleCount,
                                                          'boradCount': boardCount})
                                else:
                                    flag = True
                            else:#limit_date为空时也可发布文章
                                flag = True
                            if flag:
                                board = Board.objects.get(name=boardName)
                                if board is not None:
                                    category = board.category
                                    article = Article(title=data['title'], link=data['link'], content=data['content'],
                                                      video=data['video'],
                                                      imgs=data['imgs'], down=0, up=0, category=category, sub=boardName,
                                                      integral=0,
                                                      date=currer_datetime, year=year, week=week,
                                                      user=request.user)
                                    article.save()
                                    return HttpResponseRedirect('/personalIndex/' + str(request.user.id) + '/')
                                else:
                                    message = u'暂时还没有该圈子'
                                    return global_render(request, 'articleAdd.html',
                                                         {'form': form, 'boardName': boardName, 'message': message,
                                                          'articleCount': articleCount, 'boradCount': boardCount})
                        else:
                            message = u'您还不是高级会员，暂不能发贴'
                            return global_render(request, 'articleAdd.html',
                                                 {'form': form, 'boardName': boardName, 'message': message,
                                                  'users': request.user, 'articleCount': articleCount,
                                                  'boradCount': boardCount})
                    else:
                        message = u'您还不是高级会员，暂不能发贴'
                        return global_render(request, 'articleAdd.html',
                                             {'form': form, 'boardName': boardName, 'message': message,
                                              'users': request.user, 'articleCount': articleCount,
                                              'boradCount': boardCount})
                else:
                    return global_render(request, 'login.html')
            else:
                return global_render(request, 'articleAdd.html',
                                     {'form': form, 'boardName': boardName, 'users': request.user,
                                      'message': form.errors, 'articleCount': articleCount, 'boradCount': boardCount})
        else:
            users = request.user
            form = ArticleForm()
            return global_render(request, 'articleAdd.html',
                                 {'users': users, 'form': form, 'articleCount': articleCount, 'boradCount': boardCount})


@login_required(login_url='/login/')
def personalIndex(request, id):
    if id:
        user = User.objects.get(pk=id)
    else:
        user = request.user
    articles = Article.objects.filter(user=user).order_by('-date')[0:10]
    artCount = Article.objects.filter(user=user).count()
    category = Category.objects.order_by('id')    #文章类型查询
    return global_render(request, 'personalIndex.html',
                         {'users': request.user, 'categorys': category, 'articles': articles, 'artCount': artCount})


@csrf_exempt
def articlePreview(request):
    title = request.POST["title"]
    image = request.POST["image"]
    content = request.POST["content"]
    type = request.POST["type"]
    link = request.POST["link"]
    contentType = request.POST["contentType"]
    user = request.user
    return global_render(request, "articleReview.html",
                         {'title': title, 'image': image, 'content': content, 'user': user,
                          'date': datetime.datetime.now(),
                          'type': type, 'link': link, 'contentType': contentType})


def uploadIndex(request):
    return render_to_response('uploadfile.html')


@csrf_exempt
def uploadify_script(request):
    response = HttpResponse()
    response['Content-Type'] = "text/javascript"
    ret = "0"
    file = request.FILES.get("Filedata", None)
    if file:
        fileName = profile_upload(file)
        response.write(fileName)
        return response


def profile_upload(file):
    '''图片上传函数'''
    if file:
        path = os.path.join(settings.MEDIA_ROOT, 'image')
        fileType = str(file.name).split('.')[-1]
        file_name = str(uuid.uuid1()) + file.name[file.name.rfind('.'):]
        path_file = os.path.join(path, file_name)
        parser = open(path_file, 'wb+')
        for chunk in file.chunks():
            parser.write(chunk)
        parser.close()
        try:
            #if img.mode != "RGB":
            #img = img.convert("RGB")
            #img.save(path_file, 'jpeg', quality=100)
            image = Image.open(path_file)
            x, y = image.size
            xsize = 500
            ysize = y * xsize / x
            image.thumbnail((xsize, ysize), Image.ANTIALIAS)
            s_file_name = "s_" + file_name
            s_path = os.path.join(path, s_file_name)
            image.save(s_path)
            if fileType == 'gif':
                return file_name
            else:
                return s_file_name
        except:
            return ""
    return ""


@csrf_exempt
def profile_delte(request):
    return ''


def uploadIndex_new(request):
    return render_to_response('uploadfile_new.html')


@login_required(login_url='/login/')
def direct_message(request, userName):
    if request.method == 'POST':
        user = request.user
        userProfile = UserProfile.objects.get(user=user)
        if userProfile is not None:
            startDate = userProfile.start_date
            endDate = userProfile.end_dete
            if startDate is not None and endDate is not None:
                currDate = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
                startDate = datetime.datetime.strftime(startDate, "%Y-%m-%d %H:%M:%S")
                endDate = datetime.datetime.strftime(endDate, "%Y-%m-%d %H:%M:%S")
                if currDate > startDate and currDate < endDate:
                    dm = DirectMessage()
                    dm.to_user = User.objects.get(username=userName)
                    dm.from_user = request.user
                    dm.content = request.POST['content']
                    dm.save()
                    return HttpResponseRedirect("/")
                else:
                    return global_render(request, 'error.html', {'message': u'您还不是高级会员，不能发私信'})
            else:
                return global_render(request, 'error.html', {'message': u'您还不是高级会员，不能发私信'})
        else:
            return global_render(request, 'error.html', {'message': u'用户数据异常，请稍候再试'})
    else:
        return global_render(request, 'directMessage.html', {'to_user': userName})


@login_required(login_url='/login/')
def deldm(request, id):
    DirectMessage.objects.get(id=id).delete()
    return HttpResponseRedirect("/checkdm/")


@login_required(login_url='/login/')
def check_dm(request):
    dms = DirectMessage.objects.filter(to_user=request.user)
    DirectMessage.objects.update(is_read=1)
    return global_render(request, 'dmList.html', {'dms': dms})


@login_required(login_url='/login/')
def reportMesage(request):
    if request.method == "GET":
        type = request.GET['type']
        id = request.GET['id']
        if type is not None and id is not None:
            user = request.user
            if type == "1":
                article = Article.objects.get(id=id)
                if article is not None:
                    report = Report()
                    report.article_id = article.id

                    report.user = user
                    report.save()
                    return HttpResponse("1")
            if type == "2":
                dm = DirectMessage.objects.get(id=id)
                if dm is not None:
                    report = Report()
                    report.dm_id = dm.id

                    report.user = user
                    report.save()
                    return HttpResponse("1")
        else:
            return global_render(request, 'error.html', {'message': u'数据异常，请稍候再试'})

#申请圈子
@login_required(login_url='/login/')
def applyboard(request):
    if request.method == 'GET':
        list = Board.objects.filter(manager=request.user)
        form = BoardForm()
        return global_render(request, 'applyboard.html', {'form': form, 'list': list})
    else:
        form = BoardForm(request.POST)
        if form.is_valid():
            boardExist = Board.objects.filter(name=form.cleaned_data['name'], category=form.cleaned_data['category'])
            if boardExist:
                error = 'This category has exist the name you are apply'
                return global_render(request, 'applyboard.html', {'form': form, 'list': list, 'error': error})
            else:
                board = Board()
                board.name = form.cleaned_data['name']
                board.category = form.cleaned_data['category']
                board.about = form.cleaned_data['about']
                board.manager = request.user
                board.count = 1
                board.save()
                boardFollower = BoardFollower()
                boardFollower.board = board
                boardFollower.user = request.user
                boardFollower.save()
                return HttpResponseRedirect('/applyboard/')
                #try:
                #    send_mail('Someone apply board!',
                #              'Someone apply board,name is %s please check!' % board.name,
                #              'suyu8776@163.com', [settings.ADMIN_EMAIL], fail_silently=False)
                #except:
                #    pass
        else:
            return global_render(request, 'applyboard.html', {'form': form, 'error': form.errors})
        return HttpResponseRedirect('/applyboard/')


#我的圈子
@login_required(login_url='/login/')
def myboardlist(request):
    list = BoardFollower.objects.filter(user=request.user)
    return global_render(request, 'myboardlist.html', {'list': list, 'users': request.user})


@login_required(login_url='/login/')
def viewboard(request, boardName):
    if boardName:
        articles = Article.objects.filter(sub=boardName)[0:10]
        return render(request, 'viewborad.html', {'articles': articles,
                                                  'users': request.user,
                                                  'articleUrl': '/boardArticleIndex/' + boardName + '/'})


def gift(request, articleId):
    article = Article.objects.get(id=articleId)
    pay_to = None
    if article.user.userprofile.paypal is None:
        pay_to = settings.PAYPAL_RECEIVER_EMAIL
    else:
        pay_to = article.user.userprofile.paypal
    item_name = "Gift to the author " + article.user.username + ".<br/>"
    des = "Thanks your support,your gift will bring the author more passion to write valued article."
    invoice = uuid.uuid1()
    price = 1
    paypal_dict = {
        "business": pay_to,
        "amount": price,
        "item_name": item_name,
        "item_number": "gift",
        "invoice": invoice,
        "notify_url": "http://www.blackfers.info/paypalnotify/",
        "return_url": "http://www.blackfers.info/your-return-location/",
        "cancel_return": "http://www.blackfers.info/your-cancel-location/",
    }
    gift = Gift()
    gift.article_id = articleId
    gift.author_name = article.user.username
    gift.pay_to_paypal = pay_to
    gift.pay_invoice = invoice
    gift.price = price
    gift.save()
    form = PayPalPaymentsForm(initial=paypal_dict)
    context = {"form": form.sandbox(), 'price': price, 'description': item_name + des}
    return render_to_response("paymentad.html", context)


@login_required(login_url='/login/')
def ad(request):
    if request.method == 'GET':
        current_date = datetime.datetime.today()
        after_ads = Ad.objects.filter(start_date__gt=current_date)
        if after_ads.count() == 0:
            user_score()
        ads = Ad.objects.filter(start_date__gt=current_date, pay_pre_flag__isnull=True)
        return global_render(request, 'ad.html', {'ads': ads})
    else:
        content = request.POST['content']
        id = request.POST['id']
        ad = Ad.objects.get(id=id)
        price = 0
        if ad.pay_pre_flag is None:
            item_name = "one week ad pre fee in " + ad.category.name
            invoice = uuid.uuid1()
            paypal_dict = {
                "business": "suyu87_1349264155_biz@gmail.com",
                "amount": ad.pre_price,
                "item_name": item_name,
                "item_number": "ad_pre",
                "invoice": invoice,
                "notify_url": "http://www.blackfers.info/paypalnotify/",
                "return_url": "http://www.blackfers.info/your-return-location/",
                "cancel_return": "http://www.blackfers.info/your-cancel-location/",
            }
            ad.pay_pre_flag = 'fail'
            ad.pre_date = datetime.datetime.now()
            ad.pre_invoice = invoice
            ad.content = content
            ad.pay_user = request.user.id
            ad.save()
            price = ad.pre_price
            form = PayPalPaymentsForm(initial=paypal_dict)
            context = {"form": form.sandbox(), 'price': price, 'description': item_name}
            return render_to_response("paymentad.html", context)
        else:
            return global_render(request, 'error.html', {'message': "status error!"})


@login_required(login_url='/login/')
def myad(request):
    if request.method == 'GET':
        ads = Ad.objects.filter(pay_user=request.user.id,
                                pay_pre_flag='success',
                                check='success',
                                pay_flag__isnull=True)
        return global_render(request, 'ad.html', {'ads': ads})
    else:
        id = request.POST['id']
        ad = Ad.objects.get(id=id)
        item_name = "one week ad fee in " + ad.category.name
        invoice = uuid.uuid1()
        paypal_dict = {
            "business": ad.pay_to_paypal,
            "amount": ad.ad_price,
            "item_name": item_name,
            "item_number": "ad",
            "invoice": invoice,
            "notify_url": "http://www.blackfers.info/paypalnotify/",
            "return_url": "http://www.blackfers.info/your-return-location/",
            "cancel_return": "http://www.blackfers.info/your-cancel-location/",
        }
        ad.invoice = invoice
        ad.pay_flag = 'fail'
        ad.date = datetime.datetime.now()
        ad.save()
        form = PayPalPaymentsForm(initial=paypal_dict)
        context = {"form": form.sandbox(), 'price': ad.ad_price, 'description': item_name}
        return render_to_response("paymentad.html", context)


def contact(request):
    if request.method == 'GET':
        form = ContactForm
        return global_render(request, 'contact.html', {'form': form})
    else:
        form = ContactForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/contact/')
        else:
            return global_render(request, 'contact.html', {'form': form})


@login_required(login_url='/login/')
def senior(request):
    if request.method == 'GET':
        userprofile = request.user.userprofile
        if userprofile.paypal:
            return global_render(request, 'senior.html', {})
        else:
            return global_render(request, 'setting.html',
                                 {'userProfile': userprofile,
                                  'message': 'you must set paypal first'})
    else:
        price = request.POST['price']
        months = 1200
        item_name = months + " months senior member fee"
        invoice = uuid.uuid1()
        total_price = int(price)
        paypal_dict = {
            "business": settings.PAYPAL_RECEIVER_EMAIL,
            "amount": total_price,
            "item_name": item_name,
            "item_number": "senior",
            "invoice": invoice,
            "notify_url": "http://www.blackfers.info/paypalnotify/",
            "return_url": "http://www.blackfers.info/return-location/",
            "cancel_return": "http://www.blackfers.info/cancel-location/",
        }
        userPaysenior = UserPaySenior()
        userPaysenior.user = request.user
        userPaysenior.pay_invoice = invoice
        userPaysenior.months = months
        userPaysenior.price = price
        userPaysenior.save()
        form = PayPalPaymentsForm(initial=paypal_dict)
        context = {"form": form.sandbox(), 'price': total_price, 'description': item_name}
        return render_to_response("paymentad.html", context)


def up_vote(request, id):
    if request.user.username != '':
        try:
            vote_history = Vote_history.objects.get(user_id=request.user.id, article_id=id)
        except:
            vote_history = None
        if vote_history is None:
            article = Article.objects.get(id=id)
            article.up += 1
            article.integral = hot(article.up, article.down,
                                   datetime.datetime(article.date.year, article.date.month, article.date.day))
            article.save()
            vote_history = Vote_history()
            vote_history.article_id = id
            vote_history.user_id = request.user.id
            vote_history.ticket = 'add'
            vote_history.save()
            compute_integel(article)
            return HttpResponse("Vote success!")
        else:
            return HttpResponse("You had voted!")
    else:
        return HttpResponse("You must login first!")


def down_vote(request, id):
    if request.user.username != '':
        try:
            vote_history = Vote_history.objects.get(user_id=request.user.id, article_id=id)
        except:
            vote_history = None
        if vote_history is None:
            article = Article.objects.get(id=id)
            article.down += 1
            article.integral = hot(article.up, article.down,
                                   datetime.datetime(article.date.year, article.date.month, article.date.day))
            article.save()
            vote_history = Vote_history()
            vote_history.article_id = id
            vote_history.user_id = request.user.id
            vote_history.ticket = 'mins'
            vote_history.save()
            return HttpResponse("Vote success!")
        else:
            return HttpResponse("You had voted!")
    else:
        return HttpResponse("You must login first!")


def compute_integel(article):
    current_date = datetime.datetime.now()
    year = current_date.strftime('%Y')
    week = current_date.strftime('%W')
    d1 = datetime.datetime(article.date.year, article.date.month, article.date.day)
    d2 = datetime.datetime(current_date.year, current_date.month, current_date.day)
    if (d2 - d1).days < 8:
        user = article.user
        articles = Article.objects.filter(user=user,
                                          year=year, week=week, category=article.category)
        if articles:
            ids = [article.id for article in articles]
            vote = Vote_history.objects.filter(article_id__in=ids, ticket='add').values('user_id').distinct('user_id')
            #vote.query.group_by = ['user_id']
            vote_count = vote.count()
            article_count = articles.count()
            score = int(vote_count * 0.6 + vote_count / article_count * 0.4)
            ci = CategoryIntegral.objects.filter(user=article.user,
                                                 category=article.category, year=year, week=week)
            if ci:
                ci[0].integral = score
                ci[0].save()
            else:
                categoryIntegral = CategoryIntegral()
                categoryIntegral.user = article.user
                categoryIntegral.category = article.category
                categoryIntegral.year = year
                categoryIntegral.week = week
                categoryIntegral.integral = score
                categoryIntegral.save()


def epoch_seconds(date):
    epoch = datetime.datetime(2012, 9, 15)
    """Returns the number of seconds from the epoch to date."""
    td = date - epoch
    return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000)


def score(ups, downs):
    return ups - downs


def hot(ups, downs, date):
    """The hot formula. Should match the equivalent function in postgres."""
    s = score(ups, downs)
    order = log(max(abs(s), 1), 10)
    sign = 1 if s > 0 else -1 if s < 0 else 0
    seconds = epoch_seconds(date) - 1347725185  #到2012-09-15的秒数
    return round(order + sign * seconds / 45000, 7)

#过滤特殊字符
def qn(s):
    dirty_stuff = ["\"", "\\", "/", "*", "'", "=", "-", "#", ";", "<", ">", "+", "%"]
    for stuff in dirty_stuff:
        s = s.replace(stuff, "")
    return "'" + s + "'"


def user_score():
    current_date = datetime.datetime.today()
    weekday = current_date.strftime('%w')
    week_begin = current_date + datetime.timedelta(days=-int(weekday))
    week_before = current_date + datetime.timedelta(days=-(int(weekday)+7))
    year = week_before.strftime('%Y')
    last_week = week_before.strftime('%U')#星期天为一周开始
    week_after = week_begin + datetime.timedelta(days=7)
    two_weeks_after = week_begin + datetime.timedelta(days=14)
    categorys = Category.objects.all()
    if categorys:
        for category in categorys:
            cis = CategoryIntegral.objects.filter(category=category.name, year=int(year), week=int(last_week)).order_by(
                'integral')
            if cis:
                ad = Ad()
                ad.category = category
                if cis[0].user.userprofile.paypal:
                    ad.pay_to_paypal = cis[0].user.userprofile.paypal
                else:
                    ad.pay_to_paypal = settings.PAYPAL_RECEIVER_EMAIL
                ad.start_date = week_after
                ad.end_date = two_weeks_after
                ad.init_date = current_date
                ad.pre_price = category.pre_price
                ad.ad_price = category.price
                ad.save()

@login_required(login_url='/login/')
def kickArticle(request,articleId):
    article = Article.objects.get(pk=articleId)
    article.sub = None
    article.save()
    return ''

@login_required(login_url='/login/')
def kickUser(request,boardId,userId):
    board = Board.objects.get(pk=boardId)
    user = User.objects.get(pk=userId)
    BoardFollower.objects.get(board=board,user=user).delete()
    return ''


def Error_404(request):
    return HttpResponse("404")


def Error_500(request):
    return HttpResponse("500")



